package com.zb.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.constant.WorkConstant;
import com.zb.entity.*;
import com.zb.excel.ExcelDynamicsFieldUtil;
import com.zb.excel.entity.ExcelDynamicsField;
import com.zb.excel.entity.ExcelDynamicsFieldResult;
import com.zb.extend.*;
import com.zb.mapper.ZjWorkDispatchEngineerMapper;
import com.zb.order.service.ConWorkExportFieldSerivce;
import com.zb.service.*;
import com.zb.utils.ZbDateUtil;
import com.zb.utils.ZbManager;
import com.zb.view.ViewNetworkEmpDetail;
import com.zb.vo.OrderSettlementPriceVo;
import com.zb.vo.WorkExportAndSaveFieldVo;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author WEN
 * @Date 2024/3/4 0004
 **/
@Service
public class ConWorkExportFieldSerivceImpl implements ConWorkExportFieldSerivce {
    /**
     * Excel每页导出数量
     */
    private static int EXCEL_SHEET_DATA_SIZE = 5000;
    @Resource
    ZjWorkOrderService workOrderService;
    @Resource
    private ZjWorkOrderByFieldService workOrderByFieldService;
    @Resource
    private ZjWorkModuleService workModuleService;
    @Resource
    private ZjAccountService accountService;
    @Resource
    private ZjWorkGoodsService workGoodsService;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ViewNetworkEmpDetailService viewNetworkEmpDetailService;
    @Resource
    private ZjWorkFeeDetailService workFeeDetailService;
    @Resource
    private ZjWorkSpareMaterialService workSpareMaterialService;
    @Resource
    private ZjWorkFieldValService workFieldValService;
    @Resource
    private ZjFactoryService factoryService;
    @Resource
    private ZjWorkDetailService workDetailService;
    @Resource
    private ZjWorkLeaveMessageService workLeaveMessageService;
    @Resource
    private ZjWorkFinishOrderTemplateFieldValService workFinishOrderTemplateFieldValService;
    @Autowired
    private ZjWorkDispatchEngineerMapper zjWorkDispatchEngineerMapper;

    // 导出工单字段
    @Override
    public void orderExportField(HttpServletResponse response, AccounLoginInfo loginInfo, WorkExportAndSaveFieldVo exportFieldVo) {
        long totalCount = workOrderService.getListCount(loginInfo.getCustAccId(), exportFieldVo.getSelectVo());
        Assert.isTrue(totalCount > 0, "没有可导出的工单数据");
        // 工单系统字段
        Map<String, String> orderSysField = ExportFieldAttrVo.exportFieldAttrToMap(1, exportFieldVo.getExportFieldVo().getFieldAttrs());
        // 工单自定义字段
        Map<String, String> orderCustomField = ExportFieldAttrVo.exportFieldAttrToMap(2, exportFieldVo.getExportFieldVo().getFieldAttrs());
        // 工单结单字段
        Map<String, String> orderStatementField = ExportFieldAttrVo.exportFieldAttrToMap(3, exportFieldVo.getExportFieldVo().getFieldAttrs());
        // 工单评价字段
        Map<String, String> orderEvaluateField = ExportFieldAttrVo.exportFieldAttrToMap(4, exportFieldVo.getExportFieldVo().getFieldAttrs());
        // 获取自定义排序
        exportFieldVo.getSelectVo().setOrderBy(workOrderByFieldService.getOrderTableOrderByFieldByCustAccIdAndAccountIdAndType(loginInfo, 1, exportFieldVo.getSelectVo().getStatus()));

        ExcelWriterBuilder writerBuilder = null;
        ExcelWriter excelWriter = null;
        try {
            writerBuilder = EasyExcel.write(response.getOutputStream());
        } catch (IOException e) {
            return;
        }
        Long limit = 500L;
        exportFieldVo.getSelectVo().setLimit(limit);
        long totalPage = totalCount % limit == 0? totalCount / limit : totalCount / limit +1;
        long page = 0;
        List<WorkOrderExtend> orderList = null;
        List<Map<String, Object>> mapList = null;
        List<List<ExcelDynamicsField>> excelDynamicsFieldList = new ArrayList<>();
        ExcelDynamicsFieldResult dynamicsFieldResult = null;
        ArrayList<List<String>> excelHeader = new ArrayList<>();
        int sheetNo = 0;
        while (page < totalPage) {
            page++;
            exportFieldVo.getSelectVo().setPage(page);
            // 获取工单数据
            orderList = workOrderService.getOrderList(loginInfo.getCustAccId(), exportFieldVo.getSelectVo());
            // 处理工单数据
            mapList = handlerOrderData(orderList, orderSysField, orderCustomField, orderStatementField, orderEvaluateField);
            // 处理工单结果数据
            excelDynamicsFieldList.addAll(handlerResultData(mapList, exportFieldVo.getExportFieldVo().getFieldAttrs()));
            // 解析成导出Excel的数据
            dynamicsFieldResult = ExcelDynamicsFieldUtil.excelDynamicsFieldPack(excelDynamicsFieldList);
            // 每次1000条导出一次
            if (excelDynamicsFieldList.size() >= 50000) {
                sheetNo++;
                if (null == excelWriter) {
                    // 处理Excel表头数据
                    excelHeader.addAll(dynamicsFieldResult.getExcelHeader());
                    excelWriter = writerBuilder.head(excelHeader).build();
                }
                setWriteExcelData(sheetNo, excelWriter, dynamicsFieldResult.getExcelData());
                excelDynamicsFieldList.clear();
                dynamicsFieldResult = null;
            }
        }
        // 判断是否还有数据没有设置到Excel中
        if (null != dynamicsFieldResult) {
            if (null == excelWriter) {
                // 处理Excel表头数据
                excelHeader.addAll(dynamicsFieldResult.getExcelHeader());
                excelWriter = writerBuilder.head(excelHeader).build();
            }
            sheetNo++;
            setWriteExcelData(sheetNo, excelWriter, dynamicsFieldResult.getExcelData());
        }
        try {
            // 注：如使用中文，则需要此行代码配置，如仅使用字母，则可要可不要
            response.addHeader("Content-Disposition", "filename=order_"+ DateFormatUtils.format(new Date(), "yyyyMM") +".xlsx");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            if (null != excelWriter) {
                excelWriter.finish();
            }
        } catch (Exception e) {
            ZbManager.log.error("工单数据导出异常：" + e.getMessage());
        }
    }

    private void setWriteExcelData(int sheetNo, ExcelWriter writer, List<List<String>> excelDataList) {
        writer.write(excelDataList, EasyExcel.write().sheet(sheetNo, "No." + sheetNo).build());
    }

    private List<List<ExcelDynamicsField>> handlerResultData(List<Map<String, Object>> mapList, List<ExportFieldAttrVo> fieldAttrs) {
        List<List<ExcelDynamicsField>> excelDynamicsFieldList = new ArrayList<>();
        List<ExcelDynamicsField> dynamicsFieldList = null;
        for (Map<String, Object> map : mapList) {
            dynamicsFieldList = new ArrayList<>();
            for (ExportFieldAttrVo attr : fieldAttrs) {
                dynamicsFieldList.add(new ExcelDynamicsField(attr.getName(), map.get(attr.getType() + "_" + attr.getValue())));
            }
            excelDynamicsFieldList.add(dynamicsFieldList);
        }
        return excelDynamicsFieldList;
    }

    private List<Map<String, Object>> handlerOrderData(List<WorkOrderExtend> orderList, Map<String, String> orderSysField, Map<String, String> orderCustomField,
                                  Map<String, String> orderStatementField, Map<String, String> orderEvaluateField) {
        List<Long> workIds = orderList.stream().map(ZjWorkOrder::getId).toList();
        // 工单类型
        List<ZjWorkModule> moduleList = new ArrayList<>();
        if (null != orderSysField.get("module")) {
            moduleList.addAll(workModuleService.getPartInfoByIds(orderList.stream().map(ZjWorkOrder::getModuleId).distinct().toList()));
        }
        // 工单客服
        List<ZjAccount> accountList = new ArrayList<>();
        if (null != orderSysField.get("work_emp")) {
            accountList.addAll(accountService.getNameByIds(orderList.stream().map(ZjWorkOrder::getEmpId).distinct().toList()));
        }
        // 工单商品
        List<WorkGoodsExtend> goodsExtends = new ArrayList<>();
        if (null != orderSysField.get("work_goods_brand") || null != orderSysField.get("work_goods_model") || null != orderSysField.get("work_goods_name")
                || null != orderSysField.get("work_goods_spec") || null != orderSysField.get("work_goods_warranty_start_time") || null != orderSysField.get("work_goods_warranty_end_time")) {
            goodsExtends.addAll(workGoodsService.getByWorkIds(workIds));
        }
        // 服务商
        List<ZjNetwork> networkList = new ArrayList<>();
        if (null != orderSysField.get("network")) {
            networkList.addAll(networkService.getNameByIds(orderList.stream().map(WorkOrderExtend::getNetworkId).distinct().toList()));
        }
        // 服务商负责人
        List<ViewNetworkEmpDetail> networkManagerList = new ArrayList<>();
        if (null != orderSysField.get("network_emp") || null != orderSysField.get("network_emp_phone")) {
            networkManagerList.addAll(viewNetworkEmpDetailService.getManagerByNetworkIds(orderList.stream().map(WorkOrderExtend::getNetworkId).distinct().toList()));
        }
        // 工程师
        List<ViewNetworkEmpDetail> empDetailList = new ArrayList<>();
        if (null != orderSysField.get("network_engineer") || null != orderSysField.get("network_engineer_phone")) {
            empDetailList.addAll(viewNetworkEmpDetailService.getByNetworkEmpIds(orderList.stream().map(WorkOrderExtend::getNetworkEmpId).distinct().toList()));
        }
        // 品牌商家名称
        List<ZjFactory> factoryList = new ArrayList<>();
        boolean factory = null != orderSysField.get("factory");
        if (factory) {
            factoryList.addAll(factoryService.getNameByIds(orderList.stream().filter(f -> null != f.getFactoryId() && f.getFactoryId() > 0).map(WorkOrderExtend::getFactoryId).distinct().toList()));
        }
        // 商家结算总价 & 服务商结算总价
        List<ZjWorkFeeDetail>  workFeeDetails = new ArrayList<>();
        List<ZjWorkSpareMaterial> workSpareMaterials = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(workIds) && (null != orderSysField.get("factorySettlementTotalPrice") ||  null != orderSysField.get("networkSettlementTotalPrice"))) {
            workFeeDetails.addAll(workFeeDetailService.getOrderSettlementFeeByWorkId(workIds));
            workSpareMaterials.addAll(workSpareMaterialService.getOrderSettlementFeeByWorkId(workIds));
        }

        // 工单服务费用
        List<WorkFeeDetailExtend> feeDetailExtends = new ArrayList<>();
        if (null != orderSysField.get("work_fee_name") || null != orderSysField.get("work_fee_pay_network_price") || null != orderSysField.get("work_fee_receive_factory_price")) {
            feeDetailExtends.addAll(workFeeDetailService.getGroupByWorkIds(workIds));
        }
        // 工单配件费用
        List<WorkSpareMaterialExtend> workSpares = new ArrayList<>();
        if (null != orderSysField.get("work_spare_name") || null != orderSysField.get("work_spare_pay_network_price") || null != orderSysField.get("work_spare_receive_factory_price")) {
            workSpares.addAll(workSpareMaterialService.getOrderSpareExportFieldByWorkIds(workIds));
        }
        // 工单描述
        List<ZjWorkDetail> workDetails = new ArrayList<>();
        if (null != orderSysField.get("order_content") && CollectionUtil.isNotEmpty(workIds)) {
            QueryWrapper<ZjWorkDetail> workDetailQueryWrapper = new QueryWrapper<>();
            workDetailQueryWrapper.select("id", "content")
                            .in("id", workIds);
            workDetails.addAll(workDetailService.list(workDetailQueryWrapper));
        }
        // 服务过程
        List<ZjWorkLeaveMessage> workLeaveMessages = new ArrayList<>();
        if (null != orderSysField.get("order_service_process") && CollectionUtil.isNotEmpty(workIds)) {
            workLeaveMessages.addAll(workLeaveMessageService.getByWorkIds(workIds));
        }
        // 工单自定义字段
        List<WorkFieldValExtend> orderCustomFieldList = new ArrayList<>();
        if (null != orderCustomField && orderCustomField.size() > 0) {
            orderCustomFieldList.addAll(workFieldValService.getOrderCustomFieldExportDataByWorkIds(workIds));
        }
        // 结单字段
        List<WorkFinishOrderTemplateFieldValExtend> orderStatementFieldList = new ArrayList<>();
        if (null != orderStatementField && orderStatementField.size() > 0) {
            orderStatementFieldList.addAll(workFinishOrderTemplateFieldValService.getByWorkIds(workIds));
        }
        //  商家结算价
        List<OrderSettlementPriceVo> settlementPriceVoList = new ArrayList<>();
        if (null != orderSysField.get("factorySettlementTotalPrice") || null != orderSysField.get("networkSettlementTotalPrice")) {
            settlementPriceVoList.addAll(workOrderService.getOrderSettlementPriceByWorkId(workIds));
        }
        List<Map<String, Object>> resultMapList = new ArrayList<>();
        Map<String, Object> map = null;
        for (WorkOrderExtend order : orderList) {
            map = new HashMap<>();
            getOrderSysFieldData(map, workDetails, orderSysField, order);
            // 工单模块
            if (CollectionUtil.isNotEmpty(moduleList)) {
                map.put("1_" + "module", moduleList.stream().filter(f -> Objects.equals(f.getId(), order.getModuleId())).findFirst().map(ZjWorkModule::getName).orElse(""));
            }
            // 工单客服
            if (CollectionUtil.isNotEmpty(moduleList)) {
                map.put("1_" + "work_emp", accountList.stream().filter(f -> Objects.equals(f.getId(), order.getEmpId())).findFirst().map(ZjAccount::getName).orElse(""));
            }
            // 工单商品字段
            getOrderGoodsFieldData(map, orderSysField, order.getId(), goodsExtends);
            // 服务商
            if (CollectionUtil.isNotEmpty(networkList)) {
                map.put("1_" + "network", networkList.stream().filter(f -> Objects.equals(f.getId(),order.getNetworkId())).findFirst().map(ZjNetwork::getName).orElse(""));
            }
            // 服务商负责人
            if (null != orderSysField.get("network_emp")) {
                map.put("1_" + "network_emp", networkManagerList.stream().filter(f -> Objects.equals(f.getNetworkId(), order.getNetworkId()))
                        .findFirst().map(ViewNetworkEmpDetail::getAccountName).orElse(""));
            }
            // 服务商负责人手机号
            if (null != orderSysField.get("network_emp_phone")) {
                map.put("1_" + "network_emp_phone", networkManagerList.stream().filter(f -> Objects.equals(f.getNetworkId(), order.getNetworkId()))
                        .findFirst().map(ViewNetworkEmpDetail::getAccountPhone).orElse(""));
            }
           // 工程师
            if (null != orderSysField.get("network_engineer")) {
                map.put("1_" + "network_engineer", empDetailList.stream().filter(f -> Objects.equals(f.getId(), order.getNetworkEmpId())).findFirst()
                        .map(ViewNetworkEmpDetail::getAccountName).orElse(""));
            }
            // 工程师手机号
            if (null != orderSysField.get("network_engineer_phone")) {
                map.put("1_" + "network_engineer_phone", empDetailList.stream().filter(f -> Objects.equals(f.getId(), order.getNetworkEmpId())).findFirst()
                        .map(ViewNetworkEmpDetail::getAccountPhone).orElse(""));
            }
            // 品牌商家
            if (factory) {
                map.put("1_factory", factoryList.stream().filter(f -> Objects.equals(f.getId(), order.getFactoryId())).findFirst().map(ZjFactory::getName).orElse(""));
            }
            // 商家结算总价
            if (null != orderSysField.get("factorySettlementTotalPrice")) {
                map.put("1_" + "factorySettlementTotalPrice", order.getModulePrice()
                        .add(settlementPriceVoList.stream().filter(f -> Objects.equals(f.getWorkId(), order.getId())).findFirst()
                                .map(OrderSettlementPriceVo::getReceiveFactoryPrice).orElse(new BigDecimal("0.00")))
                        .subtract(order.getFactorySettlementDeductionPrice()));
            }
            // 服务商结算总价
            if (null != orderSysField.get("networkSettlementTotalPrice") || null != orderSysField.get("factorySettlementTotalPrice")) {
//                List<OrderSettlementPriceVo> settlementPriceVoList = workOrderService.getOrderSettlementPriceByWorkId(workIds);
                map.put("1_" + "networkSettlementTotalPrice", order.getNetworkModulePrice()
                        .add(settlementPriceVoList.stream().filter(f -> Objects.equals(f.getWorkId(), order.getId())).findFirst()
                                .map(OrderSettlementPriceVo::getPayNetworkPrice).orElse(new BigDecimal("0.00")))
                        .subtract(order.getNetworkSettlementDeductionPrice()));
            }
            // 服务过程
            if (null != orderSysField.get("order_service_process")) {
                map.put("1_" + "order_service_process", workLeaveMessages.stream().filter(f -> Objects.equals(f.getWorkId(),  order.getId())).map(message -> {
                    return "[" + (message.getEmpType() == 1? "客服" : message.getEmpType() == 2? "服务商" : message.getEmpType() == 3? "工程师" : message.getEmpType() == 4? "工单客户" : "品牌商家" )+ "]" +
                            message.getEmp() + " " + DateFormatUtils.format(message.getGmtCreate(), "yyyy-MM-dd HH:mm") + " " + message.getContent();
                }).collect(Collectors.joining("；")));
            }
            // 服务费用
            getOrderFeeFieldData(map, orderSysField, order.getId(), feeDetailExtends);
            // 工单配件费用
            getOrderSpareFieldData(map, orderSysField, order.getId(), workSpares);
            // 工单自定义字段
            getOrderCustomerFieldData(map, order.getId(), orderCustomFieldList);
            // 工单结单字段
            getOrderSettlementField(map, order.getId(), orderStatementFieldList);
            resultMapList.add(map);
        }
        return resultMapList;
    }

    /**
     * 工单系统字段
     * @param map
     * @param orderSysField
     * @param order
     */
    private void getOrderSysFieldData(Map<String, Object> map, List<ZjWorkDetail> workDetails, Map<String, String> orderSysField, WorkOrderExtend order) {
        if (null != orderSysField.get("work_no")) {
            map.put("1_" + "work_no", order.getCode());
        }
        ZjWorkEngineerSign engineerSignTime = zjWorkDispatchEngineerMapper.getEngineerSignTime(order.getId());
        if (null != engineerSignTime && engineerSignTime.getSignInTime() != null) {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(engineerSignTime.getSignInTime().toInstant(), ZoneId.systemDefault());
            String formattedDate = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            map.put("1_" + "sign_time", formattedDate);
        }
        ZjWorkDispatchEngineer engineer = zjWorkDispatchEngineerMapper.getZjWorkDispatchEngineer(order.getId());
        if (null != engineer && StringUtils.isNotBlank(engineer.getReservationDate()) && StringUtils.isNotBlank(engineer.getReservationStartTime())) {
            String reservationTime = DateTimeMergeToString(engineer.getReservationDate(), engineer.getReservationStartTime());
            map.put("1_" + "\r\nreservation_time", reservationTime);
        }
        if (null != orderSysField.get("order_end_time")) {
            String endTime = null;
            if (order.getEndTime() != null){
                endTime = order.getEndTime().toInstant().atZone(ZoneId.systemDefault())
                        .toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            map.put("1_" + "order_end_time", endTime);
        }
        if (null != orderSysField.get("create_time")) {
            map.put("1_" + "create_time", DateFormatUtils.format(order.getGmtCreate(), "yyyy-MM-dd HH:mm"));
        }
        if (null != orderSysField.get("work_status")) {
            map.put("1_" + "work_status", order.getStatus() == 1? "待派单" : order.getStatus() == 2? "待服务商确认" : order.getStatus() == 3? "处理中" : order.getStatus() == 4? "已完成" : "已取消");
        }
        if (null != orderSysField.get("work_warranty")) {
            map.put("1_" + "work_warranty", order.getOverinsured()? "保外" : "保内");
        }
        if (null != orderSysField.get("work_warranty_day")) {
            map.put("1_" + "work_warranty_day", order.getWarrantyDay());
        }
        if (null != orderSysField.get("work_total_time")) {
            String totlTime = "";
            if (order.getStatus() == WorkConstant.WORK_STATUS_4 || order.getStatus() == WorkConstant.WORK_STATUS_5) {
                totlTime = order.getStatus() == WorkConstant.WORK_STATUS_4? ZbDateUtil.getTimeLength(order.getGmtCreate(), order.getEndTime()) : ZbDateUtil.getTimeLength(order.getGmtCreate(), order.getCancelTime());
            } else {
                totlTime = ZbDateUtil.getTimeLength(order.getGmtUpdate(), new Date());
            }
            map.put("1_" + "work_total_time", totlTime);
        }
        if (null != orderSysField.get("update_time")) {
            map.put("1_" + "update_time", DateFormatUtils.format(order.getGmtUpdate(), "yyyy-MM-dd HH:mm"));
        }
        if (null != orderSysField.get("username")) {
            map.put("1_" + "username", order.getUserName());
        }
        if (null != orderSysField.get("user_phone")) {
            map.put("1_" + "user_phone", order.getUserPhone());
        }
        if (null != orderSysField.get("user_address")) {
            map.put("1_" + "user_address", new StringBuffer(order.getProvince()).append("-")
                    .append(order.getCity()).append("-")
                    .append(order.getArea()).append("-")
                    .append(order.getAddress())
            );
        }
        // 工单描述
        if (null != orderSysField.get("order_content")) {
            map.put("1_" + "order_content", workDetails.stream().filter(f -> Objects.equals(f.getId(), order.getId()))
                    .findFirst().map(ZjWorkDetail::getContent).orElse(""));
        }
    }

    /**
     * 获取工单商品数据
     * @param map
     * @param orderSysField
     * @param workId
     * @param goodsExtends
     */
    private void getOrderGoodsFieldData(Map<String, Object> map, Map<String, String> orderSysField, Long workId, List<WorkGoodsExtend> goodsExtends) {
        if (null != orderSysField.get("work_goods_code")) {
            map.put("1_" + "work_goods_code", goodsExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(goodsExtend -> {
                        return String.join("、", goodsExtend.getCodes());
                    }).distinct().collect(Collectors.joining("；")));
        }
        if (null != orderSysField.get("work_goods_brand")) {
            map.put("1_" + "work_goods_brand", goodsExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(WorkGoodsExtend::getGoodsBrand).distinct().collect(Collectors.joining("、")));
        }
        if (null != orderSysField.get("work_goods_model")) {
            map.put("1_" + "work_goods_model", goodsExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(WorkGoodsExtend::getGoodsModel).distinct().collect(Collectors.joining("、")));
        }
        if (null != orderSysField.get("work_goods_name")) {
            map.put("1_" + "work_goods_name", goodsExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(WorkGoodsExtend::getGoodsName).distinct().collect(Collectors.joining("、")));
        }
        if (null != orderSysField.get("work_goods_spec")) {
            map.put("1_" + "work_goods_spec", goodsExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(WorkGoodsExtend::getGoodsSpecName).distinct().collect(Collectors.joining("、")));
        }
        if (null != orderSysField.get("work_goods_warranty_start_time")) {
            map.put("1_" + "work_goods_warranty_start_time", goodsExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(WorkGoodsExtend::getBuyTime).distinct().map(date -> DateFormatUtils.format(date, "yyyy-MM-dd")).collect(Collectors.joining("、")));
        }
        if (null != orderSysField.get("work_goods_warranty_end_time")) {
            map.put("1_" + "work_goods_warranty_end_time", goodsExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(WorkGoodsExtend::getEndTime).distinct().map(date -> DateFormatUtils.format(date, "yyyy-MM-dd")).collect(Collectors.joining("、")));
        }
    }

    /**
     * 获取工单服务费用数据
     * @param map
     * @param orderSysField
     * @param workId
     * @param feeDetailExtends
     */
    private void getOrderFeeFieldData(Map<String, Object> map, Map<String, String> orderSysField, Long workId, List<WorkFeeDetailExtend> feeDetailExtends) {
        if (null != orderSysField.get("work_fee_name")) {
            map.put("1_work_fee_name", feeDetailExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(fee -> {
                        return StringUtils.isNotBlank(fee.getName())? fee.getName() : "";
                    }).collect(Collectors.joining("；")));
        }
        if (null != orderSysField.get("work_fee_pay_network_price")) {
            map.put("1_work_fee_pay_network_price", feeDetailExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(fee -> {
                        return null != fee.getPayNetworkPrice()? fee.getPayNetworkPrice() : new BigDecimal("0.0");
                    }).reduce(BigDecimal::add).orElse(new BigDecimal("0.0")));
        }
        if (null != orderSysField.get("work_fee_receive_factory_price")) {
            map.put("1_work_fee_receive_factory_price", feeDetailExtends.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(fee -> {
                        return null != fee.getReceiveFactoryPrice()? fee.getReceiveFactoryPrice() : new BigDecimal("0.0");
                    }).reduce(BigDecimal::add).orElse(new BigDecimal("0.0")));
        }
    }

    /**
     * 获取工单申请配件数据
     * @param map
     * @param orderSysField
     * @param workId
     * @param workSpares
     */
    private void getOrderSpareFieldData(Map<String, Object> map, Map<String, String> orderSysField, Long workId, List<WorkSpareMaterialExtend> workSpares) {
        if (null != orderSysField.get("work_spare_name")) {
            map.put("1_work_spare_name", workSpares.stream().filter(f -> Objects.equals(f.getWorkId(), workId)).map(spare -> {
                return spare.getModel() + " " + spare.getSpecName();
            }).collect(Collectors.joining("；")));
        }
        if (null != orderSysField.get("work_spare_pay_network_price")) {
            map.put("1_work_spare_pay_network_price", workSpares.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(spare -> {
                        return null != spare.getPayNetworkPrice()? spare.getPayNetworkPrice() : new BigDecimal("0.0");
                    }).reduce(BigDecimal::add).orElse(new BigDecimal("0.0")));
        }
        if (null != orderSysField.get("work_spare_receive_factory_price")) {
            map.put("1_work_spare_receive_factory_price", workSpares.stream().filter(f -> Objects.equals(f.getWorkId(), workId))
                    .map(spare -> {
                        return null != spare.getReceiveFactoryPrice()? spare.getReceiveFactoryPrice() : new BigDecimal("0.0");
                    }).reduce(BigDecimal::add).orElse(new BigDecimal("0.0")));
        }
    }

    /**
     * 工单自定义字段
     * @param map
     * @param workId
     * @param
     */
    private void getOrderCustomerFieldData(Map<String, Object> map, Long workId, List<WorkFieldValExtend> orderCustomFieldList) {
        orderCustomFieldList.stream().filter(f -> Objects.equals(f.getWorkId(), workId)).forEach(fieldVal -> {
            map.put("2_" + fieldVal.getWorkFieldId(), String.join("、", fieldVal.getValues()));
        });
    }

    /**
     * 工单结单字段
     * @param map
     * @param workId
     * @param orderStatementFieldList
     */
    private void getOrderSettlementField(Map<String, Object> map, Long workId, List<WorkFinishOrderTemplateFieldValExtend> orderStatementFieldList) {
        orderStatementFieldList.stream().filter(f -> Objects.equals(f.getWorkId(), workId)).forEach(t -> {
            map.put("3_" + t.getWorkStatementTemplateFieldId(), t.getVals().stream().map(FieldValOptionVo::getOptValue).collect(Collectors.joining("、")));
        });
    }

    public static String DateTimeMergeToString(String dateStr, String timeStr) {
        LocalDateTime dateDT = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime timeDT = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // 合并：取 dateDT 的日期 + timeDT 的时间
        LocalDateTime merged = LocalDateTime.of(
                dateDT.toLocalDate(),
                timeDT.toLocalTime()
        );

        return merged.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
}
